package fm.douban;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.ui.component.RichTextField;

public class LoginUtil {
	public RichTextField t;
	public static String[] cookies = new String[5];
	public static String UID = "";
	public static String COO = "";

	public LoginUtil() {
	}

	public static boolean login(String email, String passwd) {
		getBid();
		System.out.println("email:" + email);
		System.out.println("passwd:" + passwd);
		String url = "http://www.douban.com/accounts/login";
		HttpConnection _httpConnection = null;
		OutputStream o = null;
		try {
			_httpConnection = (HttpConnection) Connector.open(url
					+ Radio.getConnectType(), Connector.READ_WRITE);
			System.out.println("after opening.");
			_httpConnection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");
			_httpConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			_httpConnection.setRequestProperty("Accept", "*/*");
			_httpConnection.setRequestProperty("Keep-Alive", "115");
			_httpConnection.setRequestProperty("Connection", "keep-alive");
			_httpConnection.setRequestProperty("Cookie", cookies[0]);
			URLEncodedPostData postData = new URLEncodedPostData("", false);
			postData.append("form_email", email);
			postData.append("form_password", passwd);
			byte[] postDataBytes = postData.getBytes();

			_httpConnection.setRequestProperty("Content-Length", (new Integer(
					postDataBytes.length)).toString());

			_httpConnection.setRequestMethod(HttpConnection.POST);
			o = _httpConnection.openOutputStream();
			o.write(postDataBytes);
			System.out.println("after writing.");
			int code = _httpConnection.getResponseCode();
			System.out.println("response code:" + code);
			if (code == HttpConnection.HTTP_MOVED_TEMP
					|| code == HttpConnection.HTTP_OK) {
				for (int i = 0;; i++) {
					String header = _httpConnection.getHeaderField(i);
					if (header == null)
						break;
					String cookie_name = _httpConnection.getHeaderFieldKey(i);
					System.out.println("cookie:" + cookie_name + "==" + header);
					if (header.startsWith("dbcl2")) {
						cookies[1] = getCookie(header);
						UID = getUid(header);
						System.out.println("uid:" + UID);
					} else if (header.startsWith("ue")) {
						cookies[2] = getCookie(header);
					} else if (header.startsWith("bid")) {
						cookies[0] = getCookie(header);
					} else
						continue;
				}
				url = "http://douban.fm";
				return redirect(url);
			}
		} catch (IOException e) {
			System.out.println(e.getClass() + ":" + e.getMessage());
			Radio.errorDialog(SongPlayScreen._resources
					.getString(RadioResource.IO_ERROR));
			System.out.println("login failed.");
		} finally {
			try {
				if (o != null) {
					o.close();
					o = null;
				}
				if (_httpConnection != null) {
					_httpConnection.close();
					_httpConnection = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	private static void getBid() {
		String url = "http://www.douban.com/";
		HttpConnection _httpConnection = null;
		try {
			_httpConnection = (HttpConnection) Connector.open(url
					+ Radio.getConnectType(), Connector.READ_WRITE);
			System.out.println("after opening.");
			_httpConnection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");
			_httpConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			_httpConnection.setRequestProperty("Accept", "*/*");
			_httpConnection.setRequestProperty("Keep-Alive", "115");
			_httpConnection.setRequestProperty("Connection", "keep-alive");

			_httpConnection.setRequestMethod(HttpConnection.GET);
			System.out.println("after writing.");
			int code = _httpConnection.getResponseCode();
			System.out.println("response code:" + code);
			if (code == HttpConnection.HTTP_MOVED_TEMP
					|| code == HttpConnection.HTTP_OK) {
				for (int i = 0;; i++) {
					String header = _httpConnection.getHeaderField(i);
					if (header == null)
						break;
					String cookie_name = _httpConnection.getHeaderFieldKey(i);
					System.out.println("cookie:" + cookie_name + "==" + header);
					if (header.startsWith("bid")) {
						cookies[0] = getCookie(header);
					} else if (header.startsWith("ll")) {
						cookies[4] = getCookie(header);
					} else
						continue;
				}
			}
		} catch (IOException e) {
			System.out.println(e.getClass() + ":" + e.getMessage());
			Radio.errorDialog(SongPlayScreen._resources
					.getString(RadioResource.IO_ERROR));
			System.out.println("login failed.");
		} finally {
			try {
				if (_httpConnection != null) {
					_httpConnection.close();
					_httpConnection = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private static String getUid(String header) {
		int start = header.indexOf("\"");
		int end = header.indexOf(":");
		return header.substring(start + 1, end);
	}

	private static boolean redirect(String url) {
		System.out.println("request:" + url);
		HttpConnection _httpConnection = null;
		try {
			_httpConnection = (HttpConnection) Connector.open(url
					+ Radio.getConnectType(), Connector.READ_WRITE);
			System.out.println("after openning.");
			_httpConnection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");
			_httpConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			_httpConnection.setRequestProperty("Accept", "*/*");
			_httpConnection.setRequestProperty("Accept-Encoding",
					"gzip,deflate");
			System.out.println("=============Request Cookie============");

			_httpConnection.setRequestProperty("Cookie",
					cookies[0] + ";" + cookies[1] + ";" + cookies[2] + ";"
							+ (cookies[4] == null ? "" : cookies[4]));
			System.out
					.println("Request Cookie:" + cookies[0] + ";" + cookies[1]
							+ ";" + cookies[2] + ";" + (cookies[4] == null ? ""
							: cookies[4]));
			System.out.println("=============Request Cookie============");

			_httpConnection.setRequestMethod(HttpConnection.GET);
			System.out.println("before getResponseCode.");
			int responseCode = _httpConnection.getResponseCode();
			System.out.println("responseCode:" + responseCode);
			if (responseCode == HttpConnection.HTTP_OK) {
				for (int i = 0;; i++) {
					String header = _httpConnection.getHeaderField(i);
					if (header == null)
						break;
					String cookie_name = _httpConnection.getHeaderFieldKey(i);
					System.out.println("cookie:" + cookie_name + "==" + header);
					if (header.startsWith("ck")) {
						cookies[3] = getCookie(header);
					} else
						continue;
				}
				return printCookie();
			}
		} catch (IOException e) {
			System.out.println(e.getClass() + ":" + e.getMessage());
			Radio.errorDialog(SongPlayScreen._resources
					.getString(RadioResource.IO_ERROR));
		} finally {
			try {
				if (_httpConnection != null) {
					_httpConnection.close();
					_httpConnection = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	private static String getCookie(String header) {
		int end = header.indexOf(";");
		return header.substring(0, end);
	}

	private static boolean printCookie() {
		System.out.println("==================cookies===================");
		for (int i = 0; i < cookies.length; i++) {
			COO += cookies[i];
			if (i < 3)
				COO += ";";
			System.out.println(cookies[i]);
			if (cookies[i] == null)
				return false;
		}
		System.out.println("==================cookies===================");
		System.out.println("coo:" + COO);
		System.out.println("uid:" + UID);
		return true;
	}

	public static String EMAIL = "1";
	public static String PASSWORD = "1";
	public static String CHANNEL = "0";
	public static String DB_URI = "/store/home/user/documents/doub.txt";

	public static void getSavedAccount() {
		try {
			if (!checkDB())
				return;

			FileConnection file = (FileConnection) Connector.open("file://"
					+ DB_URI);
			long len = file.fileSize();
			DataInputStream input = file.openDataInputStream();
			byte[] data = new byte[(int) len];
			input.readFully(data);

			String tmp = new String(data);
			System.out.println("==========tmp:" + tmp);
			EMAIL = tmp.substring(0, tmp.indexOf(":"));
			System.out.println("==========EMAIL:" + EMAIL);
			tmp = tmp.substring(tmp.indexOf(":") + 1, tmp.length());
			System.out.println("==========tmp:" + tmp);
			PASSWORD = tmp.substring(0, tmp.indexOf(":"));
			System.out.println("==========PASSWORD:" + PASSWORD);
			CHANNEL = tmp.substring(tmp.indexOf(":") + 1, tmp.length());
			System.out.println("==========CHANNEL:" + CHANNEL);
			input.close();
			file.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static boolean checkDB() {
		FileConnection sd;
		try {
			sd = (FileConnection) Connector.open("file://" + DB_URI);
			if (sd.exists()) {
				sd.close();
				return true;
			} else {
				sd.create();
				sd.close();
			}
		} catch (Exception e) {
			System.out.println("checkdb:" + e.getClass() + "::"
					+ e.getMessage());
			return false;
		}
		return false;
	}

	public static String getEmail() {
		return EMAIL;
	}

	public static String getPasswd() {
		return PASSWORD;
	}

	public static void updateDB(String email, String passwd) {
		try {

			FileConnection file = (FileConnection) Connector.open("file://"
					+ DB_URI);

			OutputStream o = file.openOutputStream();
			CHANNEL = "1";
			EMAIL = email;
			PASSWORD = passwd;
			o.write((email + ":" + passwd + ":" + CHANNEL).getBytes());
			o.flush();
			o.close();
			file.close();
		} catch (Exception e) {
			System.out.println("checkdb:" + e.getClass() + "::"
					+ e.getMessage());
		}
	}

	public static void deleteDB() {
		try {
			FileConnection file = (FileConnection) Connector.open("file://"
					+ DB_URI);
			if (file.exists())
				file.delete();
			file.close();
		} catch (Exception e) {
			System.out.println("ERROR:" + e.getClass() + e.getMessage());
		}
	}

	public static void updateChannel(int c) {
		try {
			FileConnection file = (FileConnection) Connector.open("file://"
					+ DB_URI, Connector.WRITE);
			OutputStream o = file.openOutputStream();
			o.write((EMAIL + ":" + PASSWORD + ":" + c).getBytes());
			System.out.println("==========updateChannel:" + EMAIL + ":"
					+ PASSWORD + ":" + c);
			o.flush();
			o.close();
			file.close();
		} catch (Exception e) {
			System.out.println("updateChannel:" + e.getClass() + "::"
					+ e.getMessage());
		}
	}
}
